var lat = 20.022784;
var lng = 110.342372;
var map;
var marker;

var city_list = [["海口",110.342372,20.022784],["三亚",109.511057,18.256866],
                 ["文昌",110.804304,19.549171],["临高",109.695292,19.917063],
                 ["澄迈",110.013795,19.737512],["屯昌",110.11498,19.360335],
                 ["定安",110.377142,19.68524],["儋州",109.586058,19.526141],
                 ["琼海",110.480627,19.266448],["昌江",109.054836,19.304119],
                 ["白沙",109.45354,19.231773],["琼中",109.845058,19.040105],
                 ["万宁",110.396258,18.800856],["五指山",109.524973,18.781964],
                 ["乐东",109.179162,18.755675],["保亭",109.70794,18.643494],
                 ["陵水",110.042972,18.512177]];

function init_map(container){
	map = new BMap.Map(container); //初始化地图

	var opts = {type: BMAP_NAVIGATION_CONTROL_LARGE}; //初始化地图控件
	map.addControl(new BMap.NavigationControl(opts));
	map.enableScrollWheelZoom(); //启用滚轮放大缩小

	var point = new BMap.Point(lng, lat); //初始化地图中心点
	var icon = new BMap.Icon('http://api.map.baidu.com/images/marker_red_sprite.png', new BMap.Size(20, 32));
	marker = new BMap.Marker(point, {icon:icon}); //初始化地图标记
	marker.enableDragging(); //标记开启拖拽

	var opts = {
			  width : 250,     //信息窗口宽度
			  height: 100,     //信息窗口高度
			  title : ""  //信息窗口标题
			}
	
	var infoWindow;
	
	var gc = new BMap.Geocoder();
	//添加标记拖拽监听
	marker.addEventListener("dragend", function(e){
		//获取地址信息
	    gc.getLocation(e.point, function(rs){
	        var addr = getLocationInfo(e.point, rs);
	        infoWindow = new BMap.InfoWindow(addr, opts);  //创建信息窗口对象
	    	marker.openInfoWindow(infoWindow);
	    });
	});

	//添加标记点击监听
	marker.addEventListener("click", function(e){
	   gc.getLocation(e.point, function(rs){
		   	var addr = getLocationInfo(e.point, rs);
	        infoWindow = new BMap.InfoWindow(addr, opts);  //创建信息窗口对象
	    	marker.openInfoWindow(infoWindow);
	    }); 
	});

	map.centerAndZoom(point, 15); //设置中心点坐标和地图级别
	map.addOverlay(marker); //将标记添加到地图中
}

//显示地址信息窗口
function getLocationInfo(point, rs){
	var addComp = rs.addressComponents;
	var addr = "当前位置：" + addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber + "<br />";
	addr += "纬度: " + point.lat + ", " + "经度：" + point.lng;
	
	$("#latitude").val(point.lat);
	$("#longitude").val(point.lng);
	
	return addr;
}

function initCitySelect(id){
	var select = '切换城市&nbsp;&nbsp;<select name="city_select" onchange="resetPosition(this.value)">';
	for(i in city_list){
		select += '<option value="'+i+'">'+ city_list[i][0] +'</option>';
	}
	select += '</select>';
	
	$("#"+id).html(select);
}

function resetPosition(index){
	var lng = city_list[index][1];
	var lat = city_list[index][2];
	
	if(lng && lat){
		marker.closeInfoWindow();
		var point = new BMap.Point(lng, lat);
		marker.setPosition(point);
		map.panTo(point);
	}
}

